package com.yiqi.news.mvp.ui.fragment

import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chaychan.uikit.refreshlayout.BGANormalRefreshViewHolder
import com.chaychan.uikit.refreshlayout.BGARefreshLayout
import com.jess.arms.base.BaseFragment

import com.jess.arms.di.component.AppComponent
import com.jess.arms.integration.EventBusManager
import com.jess.arms.utils.ArmsUtils
import com.jess.arms.widget.DividerItemDecoration
import com.novel.cn.ext.dp2px
import com.yiqi.news.Constant

import com.yiqi.news.di.component.DaggerNewsListComponent
import com.yiqi.news.di.module.NewsListModule
import com.yiqi.news.mvp.contract.NewsListContract
import com.yiqi.news.mvp.presenter.NewsListPresenter

import com.yiqi.news.R
import com.yiqi.news.entity.News
import com.yiqi.news.mvp.ui.activity.NewsDetailActivity
import com.yiqi.news.mvp.ui.activity.VideoDetailActivity
import com.yiqi.news.mvp.ui.adapter.NewsAdapter
import com.yiqi.news.mvp.ui.adapter.VideoAdapter
import kotlinx.android.synthetic.main.fragment_news_list.*

class NewsListFragment : BaseFragment<NewsListPresenter>(), NewsListContract.View, BaseQuickAdapter.OnItemClickListener, BGARefreshLayout.BGARefreshLayoutDelegate {


    private var mPageIndex: Int = 1
    private val mPageSize: Int = 20

    private val mAdapter: NewsAdapter by lazy {
        return@lazy NewsAdapter()
    }
    private val mVideoAdapter: VideoAdapter by lazy {
        return@lazy VideoAdapter()
    }

    private val mChannelCode: String by lazy {
        return@lazy arguments!!.getString(Constant.CHANNEL_CODE)
    }

    private val isVideoList: Boolean  by lazy {
        return@lazy arguments!!.getBoolean(Constant.IS_VIDEO_LIST)
    }


    override fun onBGARefreshLayoutBeginLoadingMore(refreshLayout: BGARefreshLayout?): Boolean {
        return false
    }

    override fun onBGARefreshLayoutBeginRefreshing(refreshLayout: BGARefreshLayout?) {
        loadData()
    }

    override fun onItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
        var bundle = Bundle()
        bundle.putString("news_id", if (isVideoList) mVideoAdapter.getItem(position)?.id else mAdapter.getItem(position)?.id)
        ArmsUtils.startActivity(mContext, NewsDetailActivity::class.java, bundle)
    }


    override fun showNewsData(string: List<News>, tips: String) {
        refresh_layout.endRefreshing()
        tip_view.show()
        mStateView.showContent()
        setData(true, string)
        if (isVideoList) mVideoAdapter.setEnableLoadMore(true) else mAdapter.setEnableLoadMore(true)
    }

    override fun showNewsError(msg: String) {
        tip_view.show(msg)
        showMessage(msg)
        mStateView.showRetry()
        mStateView.setOnRetryClickListener { loadData() }
    }

    override fun showNewsMore(string: List<News>, tips: String) {
        setData(false, string)
    }

    override fun showNewsMoreError(msg: String) {
        mAdapter.loadMoreFail()
    }


    override fun showEmpty() {
        refresh_layout.endRefreshing()
        mStateView.showEmpty()
    }

    override fun lazyFetchData() {
        loadData()

    }


    override fun initView() {
        initRefreshLayout()
    }

    override fun initEvent() {}


    companion object {
        fun newInstance(): NewsListFragment {
            return NewsListFragment()
        }
    }


    override fun setupFragmentComponent(appComponent: AppComponent) {
        DaggerNewsListComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .newsListModule(NewsListModule(this))
                .build()
                .inject(this)
    }

    override fun initView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        return inflater.inflate(R.layout.fragment_news_list, container, false);
    }

    override fun initData(savedInstanceState: Bundle?) {
        initAdapter(isVideoList)


    }

    override fun setData(data: Any?) {

    }

    override fun showMessage(message: String) {
        ArmsUtils.snackbarText(message)
    }

    override fun launchActivity(intent: Intent) {
        ArmsUtils.startActivity(intent)
    }

    override fun killMyself() {

    }


    fun initRefreshLayout() {
        refresh_layout.setDelegate(this)
        // 设置下拉刷新和上拉加载更多的风格     参数1：应用程序上下文，参数2：是否具有上拉加载更多功能
        val refreshViewHolder = BGANormalRefreshViewHolder(mContext, false)
        // 设置下拉刷新
        refreshViewHolder.setRefreshViewBackgroundColorRes(R.color.color_F3F5F4)//背景色
        refreshViewHolder.setPullDownRefreshText(getString(R.string.refresh_pull_down_text))//下拉的提示文字
        refreshViewHolder.setReleaseRefreshText(getString(R.string.refresh_release_text))//松开的提示文字
        refreshViewHolder.setRefreshingText(getString(R.string.refresh_ing_text))//刷新中的提示文字


        // 设置下拉刷新和上拉加载更多的风格
        refresh_layout.setRefreshViewHolder(refreshViewHolder)
        refresh_layout.shouldHandleRecyclerViewLoadingMore(rv_news)
    }

    private fun initAdapter(isVideoList: Boolean) {
        rv_news.layoutManager = LinearLayoutManager(activity) as RecyclerView.LayoutManager?
        if (isVideoList) {
            mVideoAdapter.bindToRecyclerView(rv_news)
            mVideoAdapter.onItemClickListener = this
            mVideoAdapter.setOnLoadMoreListener { mChannelCode?.let { mPresenter?.getNewsDataMore(mPageIndex, mPageSize, 1, mChannelCode) } }
        } else {
            rv_news.addItemDecoration(DividerItemDecoration(DividerItemDecoration.VERTICAL).setHeight(dp2px(4)))
            mAdapter.bindToRecyclerView(rv_news)
            mAdapter.onItemClickListener = this
            mAdapter.setOnLoadMoreListener { mChannelCode?.let { mPresenter?.getNewsDataMore(mPageIndex, mPageSize, 1, mChannelCode) } }
        }
    }

//    override fun getStateViewRoot(): View {
//        return fl_content
//    }


    private fun loadData() {
        mStateView.showLoading()
        mPageIndex = 1
        mChannelCode?.let { mPresenter?.getNewsData(mPageIndex, mPageSize, 1, mChannelCode) }
    }

    private fun setData(isRefresh: Boolean, data: List<News>) {
        mPageIndex++
        val size = data?.size
        if (isRefresh) {
            if (isVideoList) mVideoAdapter.setNewData(data) else mAdapter.setNewData(data)
        } else {
            if (size > 0) {
                if (isVideoList) mVideoAdapter.addData(data) else mAdapter.addData(data)
            }
        }
        if (size < mPageSize) {
            //第一页如果不够一页就不显示没有更多数据布局
            mAdapter.loadMoreEnd(isRefresh)
        } else {
            mAdapter.loadMoreComplete()
        }
    }

}
